// page/wheat//pages/dangqi/dangqi.js
var app = getApp();
var util = app.util;
var maiList = app.http.anchor_mailistPost; //接口 排麦列表
var maiType = app.http.maiTypePost; //接口 排麦类型
var maiSubmit = app.http.savePaimaiPost; //接口 提交排麦
var canclepaimai = app.http.canclepaimaiPost; //接口 取消排麦
var setEndTime = app.http.setEndTimePost   // 接口 结束时间
var historyJiekou = app.http.historyPost //接口历史记录
var setmaiOut;  //定时器 paimai列表接口
Page({

  /*
   * 页面的初始数据
   */
  data: {
    xuanzhong: 0,         //选中排id
    hudongpai_index: 1,     //互动排默认数字
    remark:false,
    memo:'',
    Historylist:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //
    let safeAreaBottom = (wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom) * (750 / wx.getSystemInfoSync().windowWidth)
    this.setData({
      safeAreaBottom
    })
    //设置分享 
    wx.showShareMenu({
      withShareTicket: true
    })
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    //当前时间 大于 档期结束时间 则跳到首页
    var endtime = wx.getStorageSync('dangqiInfo').riqi + " " + wx.getStorageSync('dangqiInfo').endtime
    if ((new Date().getTime() > util.riqiTime(endtime)) || !wx.getStorageSync('dangqiInfo')) {
      if(!dangqiInfo){
        wx.switchTab({
          url: "/page/tabBar/wheat/index"
        })
        return;
      }
    }

    if (this.data.onList && (wx.getStorageSync('dangqiInfo').manager_id == wx.getStorageSync('userinfo').uid)){
      wx.showToast({
        title: '你已成为本档主持，麦序已取消',
        icon: 'none'
      })
   }

    this.getmaiList(true);
    //页面标题为路由参数
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    var beteenTime = dangqiInfo.starttime + " — " + dangqiInfo.endtime
    wx.setNavigationBarTitle({
      title: beteenTime
    })
    

    this.setData({
      dangqiInfo: dangqiInfo
      , beteenTime
      ,userinfo:wx.getStorageSync('userinfo')
    })
    //paimai列表  每秒调一次
    setmaiOut = setInterval(function () {
      this.getmaiList(false);
    }.bind(this), "3000")

    //paimai类型
    this.getmaiType();

    //历史接口
    this.history(); 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(setmaiOut);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(setmaiOut);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return util.shareSet(this, "排麦中");
  },
  //获取排麦列表
  getmaiList: function (flag = false) {

    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    var token = wx.getStorageSync('userinfo').token
    var hall_id = wx.getStorageSync('hall_info').id
    maiList({
      token,
      dangqiid: dangqiInfo.id,
      hall_id
    }, flag).then(re => {
      //console.log(re, "re.data");
      if (re.code == 0) {
        //判断是否跳转到 已排页面
        var dangqiInfo = wx.getStorageSync('dangqiInfo')
        

        var my_uid = wx.getStorageSync('userinfo').uid
        var onList = false
        for (let i=0; i<re.data.length; i++) {
          var item = re.data[i]
          if (item.uid == my_uid) {
            onList = true
          }
        }

        let isHost = 0 
        if (my_uid == re.zhuchi_info.manager_id){
          isHost = 1
        }

        //跳转页面
        if (re.paimaiend) {
          var time = Number(re.paimaiend) * 1000
        } else {
          var time = util.riqiTime(dangqiInfo.riqi + " " + dangqiInfo.starttime)
        }
        if (new Date().getTime() > time) {

          if(re.data.length != re.max_num){
            wx.redirectTo({
              url: '../anchor_vacancy/anchor_vacancy',
            })
          }else{
            //小程序管理员 ，主持， 主播
            if (wx.getStorageSync("userinfo").roles.indexOf("1") != -1 || isHost || onList) {
              wx.redirectTo({
                url: '../main_daka/main_daka',
              })
            } else {
              wx.redirectTo({
                url: '../anchor_yipai/anchor_yipai',
              })
            }
          }

        }


        this.setData({
          isHost,
          maiList: re.data,
          zhuchi_info: re.zhuchi_info,
          guding_num: re.guding_num,
          max_num: re.max_num,
          myuid: re.myuid,
          onList: onList,
        })

      } else {
        console.log("排麦列表接口 返数据失败");
      }
    })
  },
  //获取排麦类型
  getmaiType: function () {
    var hall_info = wx.getStorageSync('hall_info')
    var token = wx.getStorageSync('userinfo').token
    maiType({
      token,
      hall_id: hall_info.id
    },false).then(re => {
      if (re.code == 0) {
        this.setData({
          maiType: re.data,
          kejiajian: re.kejiajian,
          zishu:re.zishu
        })
      } else {
        console.log("接口返回数据失败", re);
      }
    })
  },
  //加一
  jiayi: function () {
    var hudongpai_index = this.data.hudongpai_index
    this.setData({
      hudongpai_index: hudongpai_index + 1
    })
  },
  //选中类型
  setSueType: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    this.setData({
      xuanzhong: id,
      xuanzhong_index: index,
      hudongpai_index: 1
    })
  },
  //提交
  submitPaimai: function () {

    if (!this.data.xuanzhong) {
      wx.showToast({
        title: '请选择',
        icon: 'none'
      })
      return;
    }

    //固定麦位 ：置顶卡和礼物排 顺序 置顶卡优先，礼物排钻数
    var guding_num = this.data.guding_num
    var xuanzhong_index = this.data.xuanzhong_index
    var maiType = this.data.maiType
    var maiList = this.data.maiList
    if (maiType[xuanzhong_index].type == "礼物") {
      var i = 0
      maiList.forEach(function (val, index, arr) {
        if (val["maitype"] == "礼物" || val["maitype"] == "置顶卡") {
          i++
        }
      }, this)

      if (guding_num == i) {
        maiList.forEach(function (val, index, arr) {
          if (val["maitype"] == "礼物") {
            if (Number(maiType[xuanzhong_index].num) <= Number(val["num"])) {
              wx.showToast({
                title: '礼物排已满',
                icon: 'none'
              })
              return;
            }
          }
        }, this)
      }
    }
    if (maiType[xuanzhong_index].type == "置顶卡") {
      var i = 0
      maiList.forEach(function (val, index, arr) {
        if (val["maitype"] == "置顶卡") {
          i++
        }
      }, this)
      if (guding_num == i) {
        wx.showToast({
          title: '固定麦位已满',
          icon: 'none'
        })
        return;
      }
    }

    //置顶卡id
    var card_id = '';
    if (this.data.maiList.length) {
      var maiList = this.data.maiList
      maiList.forEach(function (val, index, arr) {
        if (val["maitype"] == "置顶卡" && val["uid"] == this.data.myuid) {
          card_id = val["card_id"]
        }
      }, this)
      this.setData({
        card_id:card_id
      })
    }

    this.setData({
      remark:true
    })

    
  },
  textareaiInput:function(e){
    let that = this 
    // console.log()
    that.setData({
      memo:e.detail.value==''?'':e.detail.value
    })
  },
  closeMemo:function(){
    let that = this
    this.setData({
      remark:false
    })
  },

  submitPaimaiMemo:function(){
    //参数
    var time = util.riqiTime(wx.getStorageSync('dangqiInfo').riqi + " " + wx.getStorageSync('dangqiInfo').starttime)
  
  if (new Date().getTime() > time) {
    wx.showToast({
      title: '排麦未成功',
      icon:'none'
    })
    this.setData({
      remark:false
    })
    return;
  }

    var hall_info = wx.getStorageSync('hall_info')
    var token = wx.getStorageSync('userinfo').token
    var qid = wx.getStorageSync('dangqiInfo').id
    var typeid = this.data.xuanzhong
    var nums = this.data.hudongpai_index
    var memo = this.data.memo
    var card_id = this.data.card_id
    var that = this
    maiSubmit({
      token,
      hall_id: hall_info.id,
      typeid,
      qid,
      nums,
      card_id,
      memo
    }).then(re => {
      that.setData({
        remark:false
      })

      console.log(re);
      if (re.code == 0) {
        wx.showToast({
          title: re.info,
          icon: 'none',
          complete: function(){
            //paimai列表
            that.getmaiList();
            //paimai类型
            that.getmaiType();
            //排麦历史记录
            that.history()
          }
        })
        
        //

        that.setData({
          xuanzhong: '',
          memo:'',
         
        })
        //
        
      }else if(re.code == -1){
        wx.showToast({
          title: re.info,
          icon: 'none',
        })
         
      } else {
        console.log("接口返回数据失败", re);
      }

    })
    
  },
  //取消排麦
  cancelpaimai: function (e) {
    var that = this
    var hall_info = wx.getStorageSync('hall_info')
    var token = wx.getStorageSync('userinfo').token
    var qid = wx.getStorageSync('dangqiInfo').id
    canclepaimai({
      token,
      hall_id: hall_info.id,
      qid
    }).then(re => {
      console.log(re);
      if (re.code == 0) {
        //paimai列表
        that.getmaiList();
        //paimai类型
        that.getmaiType();
        //选中的类型取消
        that.setData({
          xuanzhong: ''
        })
      } else {
        console.log("接口返回数据失败", re);
      }
    })
  },
  //更换主持人
  updatemainUrl(){

    let dangqiInfo = wx.getStorageSync("userinfo")
    if (dangqiInfo.roles.indexOf("1") > -1) {
      wx.navigateTo({
        url: "../xcx_chair/xcx_chair"
      });
    } else {
      wx.navigateTo({
        url: "../xcx_chairChange/xcx_chairChange"
      });
    }

  },
  //定时弹框显示
  dingshiModel() {
    //获取弹框标签
    var bottomDialog = this.selectComponent("#bottomDialog")
    //设置时间选中
    var timeIndex = [];
    var time_arr = wx.getStorageSync('dangqiInfo').starttime.split(":");
    var hours = bottomDialog.data.hours;
    var minute = bottomDialog.data.minute;
    // timeIndex.push(hours.indexOf(String(time_arr[0])));
    // timeIndex.push(minute.indexOf(String(time_arr[1])));
    timeIndex.push(time_arr[0]);
    timeIndex.push(time_arr[1]);
    //设置
    bottomDialog.setData({
      title: '定时结束',
      modelType: "time",
      timeIndex: timeIndex,
      guodu: timeIndex,
      hideFlag: false
    })
    bottomDialog.showModal();
  },
  //定时弹框 里面的 确定按钮
  timeSure(e) {
    console.log(e);
    //档期
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    // 定时结束时间必须大于等于当前时间  或  定时结束时间小于结束时间endtime
    var time_array = e.detail
    var riqi = dangqiInfo.riqi.split("-").join("/")
    var paimaishijian = riqi + " " + time_array[0] + ":" + time_array[1]
    var endtime = new Date(paimaishijian).getTime(); //定时结束时间
    var curtime = new Date().getTime();
    if (curtime > endtime) {
      wx.showToast({
        title: '定时时间不能小于当前时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    var end = new Date(riqi + " " + dangqiInfo.starttime).getTime(); //定时结束时间
    if (endtime > end) {
      wx.showToast({
        title: '定时时间不能大于开始时间',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    
    //接口
    var did = dangqiInfo.id
    var token = wx.getStorageSync('userinfo').token
    setEndTime({
      token,
      did: did,
      paimaiend: time_array[0] + ":" + time_array[1]
    }).then(re => {
      console.log(re);
      if (re.code == 0) {
        //设置定时
        dangqiInfo.paimaiend = time_array[0] + ":" + time_array[1];
        wx.setStorageSync('dangqiInfo', dangqiInfo);
        //修改data 
        this.setData({
          dangqiInfo: dangqiInfo
        })
        wx.showToast({
          title: '定时设置成功',
          icon:'none'
        })
      } else {
        console.log("接口返回数据失败", re);
      }
    })
  },
  //手动结束 
  gameover() {
    //档期
    var dangqiInfo = wx.getStorageSync('dangqiInfo')
    //当期时间 时分秒
    var hour = new Date().getHours()
    var minutes = new Date().getMinutes()
    //接口
    var did = dangqiInfo.id
    var token = wx.getStorageSync('userinfo').token
    setEndTime({
      token,
      did: did,
      paimaiend: hour + ":" + minutes
    }).then(re => {
      console.log(re);
      if (re.code == 0) {
        //设置定时
        dangqiInfo.paimaiend = hour + ":" + minutes;
        wx.setStorageSync('dangqiInfo', dangqiInfo);
        //跳转页面 
        wx.redirectTo({
          url: "../main_daka/main_daka"
        })
      } else {
        console.log("接口返回数据失败", re);
      }
    })

  },
  //历史接口
  history(){
    var that = this
    var token = wx.getStorageSync('userinfo').token;
    var qid = wx.getStorageSync('dangqiInfo').id
    historyJiekou({
        token,
        qid,
    },false).then(res=>{
          if(res.code == 0){
              that.setData({
                  Historylist:res.data
              })
          }
    })
  },
  //查看更多弹框历史列表
  bindmark(){
    this.history()
    this.setData({
      mask:1
    })
  },
})